#! /usr/bin/env python
# -*- coding: utf-8 -*-

from Producer import Producer
from Consumer import Consumer
from Queue import Queue
import logging


class ReaperController():
    
    def __init__(self, dbconn, contracts, connectparams):         
        self.contracts     = contracts
        self.connectparams = connectparams
        self.queue         = Queue()
        self.producer      = Producer(self.contracts, self.queue, self.connectparams)
        self.consumer      = Consumer(dbconn, self.contracts, self.queue)                
        self.isrunning     = False
                
    def start(self):           
        logging.getLogger().debug("Starting reaper")
        if self.producer.connected:
            self.consumer.start()
            self.producer.start()          
            self.isrunning = True            
        else:
            logging.getLogger().debug("Produce is not connected. Please check connection parameters")
        
        return self.isrunning
        
    def stop(self):          
        logging.getLogger().debug("Stopping reaper")
        self.consumer.stop()
        self.producer.stop()                        
                        
        if self.isrunning:
            self.consumer.join()
            self.producer.join() 
        
        self.isrunning = False    
        logging.getLogger().debug("Reaper stopped")

       
    def __del__(self):        
        if self.isrunning:   
            self.stop()        



